//
//  NameSettingVC.swift
//  WeFamily
//
//  Created by 崔世强 on 2020/7/7.
//  Copyright © 2020 Meak Tsui. All rights reserved.
//

import UIKit

class NameSettingVC: UITableViewController {

    @IBOutlet weak var nameTextField: UITextField!
    @IBOutlet weak var doneBtn: UIBarButtonItem!
    
    lazy var userService = UserService()
    
    var originName:String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let Defaults = UserDefaults(suiteName: USER_DEFAULTS_NAME)!
        
        originName = Defaults[.username] ?? ""

        nameTextField.text = Defaults[.username]
        
        nameTextField.addTarget(self, action: #selector(valueChanged), for: .editingChanged)
    }
    
    @IBAction func doneBtnClick(_ sender: Any) {
        guard let name = nameTextField.text else {
            return
        }
        self.view.makeToastActivity(.center)
        let uid = AppStatusManager.instance.userLoginStatus.1 ?? 0
        userService.updateMyInfo(uid, name: name) { success, msg in
            DispatchQueue.main.async {
                self.view.hideModalToastActivity()
                if (success) {
                    self.navigationController?.popViewController(animated: true)
                } else {
                    self.view.makeToast("修改失败", duration: 3.0, position: .center)
                }
            }
        }
    }
    
    @objc func valueChanged() {
        guard let name = nameTextField.text else {
            doneBtn.isEnabled = false
            return
        }
        if name != "",name != originName {
            doneBtn.isEnabled = true
        } else {
            doneBtn.isEnabled = false
        }
    }
}
